package com.khyr.Service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.khyr.Dao.*;
import com.khyr.Service.ReturnPremiumService;
import com.khyr.entity.*;
import com.khyr.feign.UserFeign;
import com.khyr.utils.SnowflakeIdGenerator;
import com.khyr.vo.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author ：lyk
 * @date ：Created in 2025/3/14 09:20
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class ReturnPremiumServiceImpl implements ReturnPremiumService {
    @Autowired
    private CareHistoryDao careHistoryDao;
    @Autowired
    private CareOrdersDao careOrdersDao;
    @Autowired
    private HisOrderChargeItemDao hisOrderChargeItemDao;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HisOrderBackfeeDao hisOrderBackfeeDao;
    @Autowired
    private HisOrderBackfeeItemDao hisOrderBackfeeItemDao;
    @Autowired
    private CareOrderItemDao careOrderItemDao;
    @Autowired
    private CareOrdersDao careOrderDao;
    @Override
    public GetChargedCareHistoryByRegIdReturnVo getChargedCareHistoryByRegId(String regId) {
        QueryWrapper<CareHistory> hisCareHistoryQueryWrapper = new QueryWrapper<>();
        hisCareHistoryQueryWrapper.eq("reg_id", regId);
        CareHistory careHistory = careHistoryDao.selectOne(hisCareHistoryQueryWrapper);
        List<CareOrder> careOrdersByPatientId = careOrdersDao.getChargedCareHistoryByRegId(careHistory.getPatientId());
        return new GetChargedCareHistoryByRegIdReturnVo(careHistory,careOrdersByPatientId);
    }

    @Override
    public R<String> createOrderBackfeeWithCash(OrderBackfeeVO orderBackfeeVO) {
        List<HisOrderBackfeeItem> orderBackfeeItemDtoList = orderBackfeeVO.getOrderBackfeeItemDtoList();
        HisOrderBackfee hisOrderBackfee = orderBackfeeVO.getOrderBackfeeDto();
        hisOrderBackfee.setBackId("ODB"+SnowflakeIdGenerator.nextId());
        hisOrderBackfee.setBackStatus("1");
        hisOrderBackfee.setBackType("0");
        Set<String> orderIds = new HashSet<>();
        Set<String> itemIds = new HashSet<>();
        for (HisOrderBackfeeItem hisOrderBackfeeItem : orderBackfeeItemDtoList){
            itemIds.add(hisOrderBackfeeItem.getItemId());
            String orderId = hisOrderChargeItemDao.selectById(hisOrderBackfeeItem.getItemId()).getOrderId();
            orderIds.add(orderId);
            hisOrderBackfeeItem.setBackId(hisOrderBackfee.getBackId());
            hisOrderBackfeeItem.setStatus("2");
            hisOrderBackfeeItemDao.insert(hisOrderBackfeeItem);
        }
        hisOrderBackfee.setOrderId(JSON.toJSONString(orderIds));
        hisOrderBackfee.setCreateTime(new Date());
        hisOrderBackfee.setUpdateTime(new Date());
        hisOrderBackfee.setBackTime(new Date());
        String name=userFeign.getUserInfo(request.getHeader("token")).getData().getUserName();
        hisOrderBackfee.setCreateBy(name);
        hisOrderBackfee.setUpdateBy(name);
        int insert = hisOrderBackfeeDao.insert(hisOrderBackfee);
        QueryWrapper<HisOrderChargeItem> hisOrderChargeItemQueryWrapper = new QueryWrapper<>();
        hisOrderChargeItemQueryWrapper.in("item_id",itemIds);
        List<HisOrderChargeItem> hisOrderChargeItems = hisOrderChargeItemDao.selectList(hisOrderChargeItemQueryWrapper);
        for (HisOrderChargeItem item : hisOrderChargeItems) {
            item.setStatus("2");
            hisOrderChargeItemDao.updateById(item);
        }
        QueryWrapper<CareOrderItem> careOrderItemQueryWrapper = new QueryWrapper<>();
        careOrderItemQueryWrapper.in("item_id",itemIds);
        List<CareOrderItem> careOrderItems = careOrderItemDao.selectList(careOrderItemQueryWrapper);
        for (CareOrderItem item : careOrderItems) {
            item.setStatus("2");
            careOrderItemDao.updateById(item);
        }
        if (insert>0){
            return new R<>(200,"创建成功",null);
        }else{
            return new R<>(500,"创建失败",null);
        }
    }

    @Override
    public R<Page<HisOrderBackfee>> queryAllOrderBackfeeForPage(QueryParamsVo queryParamsVo) {
        QueryWrapper<HisOrderBackfee> queryWrapper=new QueryWrapper<>();
        // 根据 noticeVo 中的条件动态构建查询条件
        if (queryParamsVo.getRegId() != null) {
            queryWrapper.like("reg_id", queryParamsVo.getRegId());
        }
        if(StringUtils.hasText(queryParamsVo.getPatientName())){
            queryWrapper.like("patient_name", queryParamsVo.getPatientName());
        }
        Page<HisOrderBackfee> page = new Page<>(queryParamsVo.getPageNum(), queryParamsVo.getPageSize());
        Page<HisOrderBackfee> p = hisOrderBackfeeDao.selectPage(page, queryWrapper);
        if (p.getTotal()>0){
            return new R<>(200,"查询成功",p);
        }else {
            return new R<>(500,"查询失败",null);
        }
    }

    @Override
    public List<HisOrderBackfeeItem> queryOrderBackfeeItemByBackId(String backId) {
        QueryWrapper<HisOrderBackfeeItem> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("back_id",backId);
        return hisOrderBackfeeItemDao.selectList(queryWrapper);
    }
    @Override
    public R<HisOrderCharge> back(String chId) {
        CareHistory careHistory = careHistoryDao.selectById(chId);
        List<CareOrder> careOrders = careOrderDao.getCareOrderItemByChId(chId,1);
        BigDecimal totalMoney = BigDecimal.ZERO;
        Set<String> itemIds = new HashSet<>();
        Set<String> orderIds = new HashSet<>();
        for (CareOrder careOrder : careOrders){
            List<CareOrderItem> careOrderItems = careOrder.getCareOrderItems();
            orderIds.add(careOrder.getCoId());
            for (CareOrderItem careOrderItem : careOrderItems){
                itemIds.add(careOrderItem.getItemId());
                totalMoney = totalMoney.add(careOrderItem.getAmount());
            }
        }
        HisOrderBackfee hisOrderBackfee = new HisOrderBackfee();
        hisOrderBackfee.setBackId("ODB"+SnowflakeIdGenerator.nextId());
        hisOrderBackfee.setBackStatus("1");
        hisOrderBackfee.setBackType("0");
        hisOrderBackfee.setBackAmount(totalMoney);
        hisOrderBackfee.setChId(chId);
        hisOrderBackfee.setRegId(careHistory.getRegId());
        hisOrderBackfee.setPatientName(careHistory.getPatientName());
        hisOrderBackfee.setBackStatus("1");
        hisOrderBackfee.setBackType("1");
        hisOrderBackfee.setCreateTime(new Date());
        hisOrderBackfee.setBackTime(new Date());
        hisOrderBackfee.setUpdateTime(new Date());
        hisOrderBackfee.setCreateBy(careHistory.getPatientName());
        hisOrderBackfee.setUpdateBy(careHistory.getPatientName());
        hisOrderBackfee.setOrderId(JSON.toJSONString(orderIds));
        int insert = hisOrderBackfeeDao.insert(hisOrderBackfee);
        QueryWrapper<CareOrderItem> careOrderItemQueryWrapper = new QueryWrapper<>();
        careOrderItemQueryWrapper.in("item_id",itemIds);
        List<CareOrderItem> careOrderItems = careOrderItemDao.selectList(careOrderItemQueryWrapper);
        for (CareOrderItem item : careOrderItems) {
            HisOrderBackfeeItem hisOrderBackfeeItem = new HisOrderBackfeeItem();
            hisOrderBackfeeItem.setItemId(item.getItemId());
            hisOrderBackfeeItem.setItemName(item.getItemName());
            hisOrderBackfeeItem.setItemPrice(item.getPrice());
            hisOrderBackfeeItem.setItemNum(item.getNum());
            hisOrderBackfeeItem.setItemAmount(item.getAmount());
            hisOrderBackfeeItem.setBackId(hisOrderBackfee.getBackId());
            hisOrderBackfeeItem.setItemType(item.getItemType());
            hisOrderBackfeeItem.setStatus("2");
            item.setStatus("2");
            careOrderItemDao.updateById(item);
        }
        QueryWrapper<HisOrderChargeItem> hisOrderChargeItemQueryWrapper = new QueryWrapper<>();
        hisOrderChargeItemQueryWrapper.in("item_id",itemIds);
        List<HisOrderChargeItem> hisOrderChargeItems = hisOrderChargeItemDao.selectList(hisOrderChargeItemQueryWrapper);
        for (HisOrderChargeItem item : hisOrderChargeItems) {
            item.setStatus("2");
            hisOrderChargeItemDao.updateById(item);
        }
        if (insert>0){
            return new R<>(200,"修改",null);
        }
        return new R<>(500,"修改失败",null);
    }
}
